package org.jeecg.modules.api.sjtbApi.controller;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.api.sjtbApi.vo.FpxxSyncParam;
import org.jeecg.modules.api.sjtbApi.vo.FpxxSyncRtn;
import org.jeecg.modules.xxgx.fpgl.entity.CsXxFpxx;
import org.jeecg.modules.xxgx.fpgl.service.ICsXxFpxxService;
import org.jeecg.modules.xxgx.fpjf.service.ICsXxJfjlService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * 数据同步API
 */
@RestController
@RequestMapping(CommonConstant.API+"/sjtb")
@Slf4j
public class SjtbController {
    @Autowired
    private ICsXxFpxxService csXxFpxxService;
    @Autowired
    private ICsXxJfjlService csXxJfjlService;

    @AutoLog(value = "发票信息数据同步接口")
    @PostMapping(value = "/fpxxSync")
    public Result<FpxxSyncRtn> fpxxSync(@RequestBody @Valid FpxxSyncParam param, BindingResult bindingResult) {
        StringBuilder errMsg = new StringBuilder();
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                String defaultMessage = objectError.getDefaultMessage();
                errMsg.append(defaultMessage).append(",");
            }
        }
        if(errMsg.length() > 0){
            return Result.error(errMsg.toString());
        }
        String tenantId = TenantContext.getTenant();
        //租户ID改成当前接口分配的租户ID
        param.setTenantId(Integer.parseInt(tenantId));

        CsXxFpxx csXxFpxx = new CsXxFpxx();
        BeanUtils.copyProperties(param, csXxFpxx);

        //生成交付URL
        csXxFpxxService.saveOrUpdate(csXxFpxx);

        String fpjfUrl = csXxJfjlService.genFpjfShortUrlPT(csXxFpxx);
        FpxxSyncRtn fpxxSyncRtn = new FpxxSyncRtn();
        fpxxSyncRtn.setId(csXxFpxx.getId());
        fpxxSyncRtn.setFpjfurl(fpjfUrl);
        return Result.OK("成功",fpxxSyncRtn);
    }
}
